package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.Utils.SMSUtils;
import com.itheima.Utils.ValidateCodeUtils;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;


    @RequestMapping("/send4Order")
    public Result send4Order(String telephone) {

        //随机发送验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        //给用户发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code.toString());
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //验证码发送成功,需要将验证码保存到redis中,时间为5分钟
        Jedis resource = jedisPool.getResource();
        resource.setex(telephone + RedisMessageConstant.SENDTYPE_ORDER, 3000, code.toString());
        resource.close();
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    @RequestMapping("/send4Login")
    public Result send4Login(String telephone) {
        //随机生成6为验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
        //给用户发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, validateCode.toString());
        } catch (ClientException e) {
            e.printStackTrace();
            //发送失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //发送成功,需要将验证码保存袋redis中,时间为5分钟
        Jedis resource = jedisPool.getResource();
        resource.setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN, 3000, validateCode.toString());
        resource.close();
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
